﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Scheduler;
using QuickTasks.ViewModels.Tables;
using LocalSettings;
using QuickTasks.ViewModels.Data;
using Microsoft.Advertising.Mobile.UI;
using Microsoft.Phone.Shell;

namespace QuickTasks.Views.ToDoList
{
    public partial class RemindersAlarms : PhoneApplicationPage
    {
       string Title = "";
        string Description = "";
        string cat = "";
        string Time = "";
        string Date = "";
        string listid = null;
        DateTime beginTime;
        Uri navigationUri;
        string name = "";
        string dateandtime = "";
        string remid = string.Empty;
        string remindertype = string.Empty;
        string reminderid = string.Empty;
        public RemindersAlarms()
        {
            InitializeComponent();
    
            Loaded += new RoutedEventHandler(Reminder_Loaded);
        }
      
        protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
        {
            try
            {
                PhoneApplicationService.Current.State["isbacknav"] = true;
            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  OnBackKeyPress event In RemindersAlarms.xaml page", ex);
            }
        }
        protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
        {

           
           NavigationContext.QueryString.TryGetValue("title", out Title);
           NavigationContext.QueryString.TryGetValue("des", out Description);
           NavigationContext.QueryString.TryGetValue("date", out Date);
           NavigationContext.QueryString.TryGetValue("cat", out cat);
           NavigationContext.QueryString.TryGetValue("time", out Time);
           NavigationContext.QueryString.TryGetValue("listid", out listid);
           NavigationContext.QueryString.TryGetValue("datetime", out dateandtime);
           NavigationContext.QueryString.TryGetValue("rt", out remindertype);

           beginTime = Convert.ToDateTime(dateandtime);
           
        }
        void Reminder_Loaded(object sender, RoutedEventArgs e)
        {
            //if (remindertype == "location")
            //{
            //    Tbxtime.IsEnabled = false;
            //    alarmRadioButton.IsEnabled = false;
            //}
            try
            {
                if (listid != "")
                {
                    using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                    {
                        var uniquevalue = from r in context.reminderalr where r.id.ToString() == listid select r;
                        foreach (var u in uniquevalue)
                        {
                            name = u.Rguid;
                            titleTextBox.Text = u.title;
                            tbxdes.Text = u.description;
                            if (u.type == "loc")
                            {

                                //reminderRadioButton.IsChecked = true;
                            }
                            else
                            {
                                if (u.type == "alaram")
                                {
                                    alarmRadioButton.IsChecked = true;

                                }
                                else
                                {
                                    reminderRadioButton.IsChecked = true;

                                }
                            }
                            //Tbxtime.Text = u.TimeDifference;
                            break;
                        }

                    }
                }
                else
                {
                    titleTextBox.Text = Title;
                    tbxdes.Text = Description;
                }

            }
            catch (Exception ex)
            {
                Exceptions.SaveOrSendExceptions("Exception in  Reminder_Loaded event In RemindersAlarms.xaml page", ex);
            }
        }

        private void ApplicationBarIconButton_Click(object sender, EventArgs e)
        {
            try
            {
                if (listid == "")
                {
                    name = System.Guid.NewGuid().ToString();
                }

                navigationUri = new Uri("/Views/ToDoList/ToDoList.xaml?r=" + remid, UriKind.Relative);
                if (remindertype == "time")
                {
                    if ((bool)reminderRadioButton.IsChecked)
                    {
                        if (listid != "")
                        {
                            string DefaultPlace = "";
                            if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                            {
                                DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                            }
                            else
                            {
                                DefaultPlace = "1";
                            }

                            using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                            {
                                IQueryable<Reminders> rowexists = from v in context.reminderalr where v.id.ToString() == listid select v;
                                Reminders remin = rowexists.FirstOrDefault();
                                {

                                    remin.Rguid = name;
                                    remin.id = int.Parse(listid);
                                    remin.title = titleTextBox.Text;
                                    remin.type = "reminder";
                                    remin.description = tbxdes.Text;
                                    remin.TimeDifference = "1";

                                    remin.begintime = Convert.ToString(beginTime.AddMinutes(1));
                                    remin.endtime = Convert.ToString(beginTime.AddMinutes(2));
                                    remin.place = DefaultPlace;

                                };


                                context.SubmitChanges();
                            }

                        }
                        else
                        {
                            using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                            {

                                int tid = 0;
                                string DefaultPlace = "";
                                if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                                {
                                    DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                                }
                                else
                                {
                                    DefaultPlace = "1";
                                }
                                var xquery = from a in context.Todo
                                             orderby a.id descending
                                             select a.id;
                                if (xquery.Count() <= 0)
                                {
                                    tid = 1;
                                }
                                else
                                {
                                    var xquery1 = from a in context.Todo
                                                  orderby a.id descending
                                                  select a;


                                    foreach (var query in xquery1)
                                    {

                                        tid = Convert.ToInt32(query.id) + 1;
                                        break;
                                    }
                                }
                                remid = tid.ToString();
                                Reminders remin = new Reminders()
                                {

                                    Rguid = name,
                                    id = tid,
                                    title = titleTextBox.Text,
                                    type = "reminder",
                                    description = tbxdes.Text,
                                    TimeDifference = "1",

                                    begintime = Convert.ToString(beginTime.AddMinutes(1)),
                                    endtime = Convert.ToString(beginTime.AddMinutes(2)),
                                    place = DefaultPlace

                                };

                                context.reminderalr.InsertOnSubmit(remin);
                                context.SubmitChanges();
                            }
                        }
                        navigationUri = new Uri("/Views/ToDoList/ToDoList.xaml?r=" + remid, UriKind.Relative);
                        Reminder reminder = new Reminder(name);
                        reminder.Title = titleTextBox.Text;
                        reminder.Content = tbxdes.Text;

                        reminder.BeginTime = beginTime.AddMinutes(1);
                        reminder.ExpirationTime = beginTime.AddMinutes(2);
                        reminder.NavigationUri = navigationUri;
                        if (ScheduledActionService.Find(name) != null)
                        {
                            ScheduledActionService.Remove(name);
                            ScheduledActionService.Add(reminder);
                        }
                        else
                        {
                            ScheduledActionService.Add(reminder);
                        }
                    }

                    if ((bool)alarmRadioButton.IsChecked)
                    {
                        if (listid != "")
                        {
                            string DefaultPlace = "";
                            if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                            {
                                DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                            }
                            else
                            {
                                DefaultPlace = "1";
                            }
                            using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                            {
                                IQueryable<Reminders> rowexists = from v in context.reminderalr where v.id.ToString() == listid select v;
                                Reminders remin = rowexists.FirstOrDefault();
                                {

                                    remin.Rguid = name;
                                    remin.id = int.Parse(listid);
                                    remin.title = titleTextBox.Text;
                                    remin.type = "alaram";
                                    remin.description = tbxdes.Text;
                                    remin.TimeDifference = "1";

                                    remin.begintime = Convert.ToString(beginTime.AddMinutes(1));
                                    remin.endtime = Convert.ToString(beginTime.AddMinutes(2));
                                    remin.place = DefaultPlace;

                                };


                                context.SubmitChanges();
                            }

                        }
                        else
                        {
                            using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                            {

                                int tid = 0;
                                string DefaultPlace = "";
                                if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                                {
                                    DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                                }
                                else
                                {
                                    DefaultPlace = "1";
                                }
                                var xquery = from a in context.Todo
                                             orderby a.id descending
                                             select a.id;
                                if (xquery.Count() <= 0)
                                {
                                    tid = 1;
                                }
                                else
                                {
                                    var xquery1 = from a in context.Todo
                                                  orderby a.id descending
                                                  select a;


                                    foreach (var query in xquery1)
                                    {

                                        tid = Convert.ToInt32(query.id) + 1;
                                        break;
                                    }
                                }
                                remid = tid.ToString();
                                Reminders remin = new Reminders()
                                {
                                    Rguid = name,
                                    id = tid,
                                    title = titleTextBox.Text,
                                    type = "alaram",
                                    TimeDifference = "1",
                                    description = tbxdes.Text,

                                    begintime = Convert.ToString(beginTime.AddMinutes(1)),
                                    endtime = Convert.ToString(beginTime.AddMinutes(2)),
                                    place = DefaultPlace

                                };

                                context.reminderalr.InsertOnSubmit(remin);
                                context.SubmitChanges();
                            }
                        }
                        Alarm alarm = new Alarm(name);
                        alarm.Content = titleTextBox.Text;
                        alarm.Sound = new Uri("/Ringtones/smokealarm.wav", UriKind.Relative);
                        alarm.BeginTime = beginTime.AddMinutes(1);
                        alarm.ExpirationTime = beginTime.AddMinutes(2);
                        if (ScheduledActionService.Find(name)!=null)
                        {
                            ScheduledActionService.Remove(name);
                            ScheduledActionService.Add(alarm);
                        }
                        else
                        {
                            ScheduledActionService.Add(alarm);
                        }
                    }
                }

                //if (remindertype=="location")
                // {
                //     if (listid != "")
                //     {
                //         string DefaultPlace = "";
                //         if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                //         {
                //             DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                //         }
                //         else
                //         {
                //             DefaultPlace = "1";
                //         }
                //         using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                //         {
                //             IQueryable<Reminders> rowexists = from v in context.reminderalr where v.id.ToString() == listid select v;
                //             Reminders remin = rowexists.FirstOrDefault();
                //             {

                //                 remin.Rguid = name;
                //                 remin.id = int.Parse(listid);
                //                 remin.title = titleTextBox.Text;
                //                 remin.type = "loc";
                //                 remin.description = tbxdes.Text;
                //                 remin.TimeDifference = "";

                //                 remin.begintime = Convert.ToString(beginTime);
                //                 remin.endtime = Convert.ToString(beginTime.AddMinutes(1));
                //                 remin.place = DefaultPlace;

                //             };


                //             context.SubmitChanges();
                //         }

                //     }
                //     else
                //     {
                //         using (QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString))
                //         {

                //             int tid = 0;
                //             string DefaultPlace = "";
                //             if (IsolatedSettings.getSettingsStringValue("DefaultPlace") != "")
                //             {
                //                 DefaultPlace = IsolatedSettings.getSettingsStringValue("DefaultPlace");
                //             }
                //             else
                //             {
                //                 DefaultPlace = "1";
                //             }
                //             var xquery = from a in context.Todo
                //                          orderby a.id descending
                //                          select a.id;
                //             if (xquery.Count() <= 0)
                //             {
                //                 tid = 1;
                //             }
                //             else
                //             {
                //                 var xquery1 = from a in context.Todo
                //                               orderby a.id descending
                //                               select a;


                //                 foreach (var query in xquery1)
                //                 {

                //                     tid = Convert.ToInt32(query.id) + 1;
                //                     break;
                //                 }
                //             }
                //             remid = tid.ToString();
                //             Reminders remin = new Reminders()
                //            {
                //                Rguid = name,
                //                id = tid,
                //                title = titleTextBox.Text,
                //                type = "loc",
                //                description = tbxdes.Text,
                //                TimeDifference = Tbxtime.Text,
                //                begintime = Convert.ToString(beginTime),
                //                endtime = Convert.ToString(beginTime.AddMinutes(1)),
                //                place = DefaultPlace

                //            };

                //             context.reminderalr.InsertOnSubmit(remin);
                //             context.SubmitChanges();
                //         }


                //     }

                //     navigationUri = new Uri("/Views/ToDoList/ToDoList.xaml?r=" + remid, UriKind.Relative);
                //     Reminder reminder = new Reminder(name);
                //     reminder.Title = titleTextBox.Text;
                //     reminder.Content = tbxdes.Text;

                //     reminder.BeginTime = beginTime;
                //     reminder.ExpirationTime = beginTime.AddMinutes(1);
                //     reminder.NavigationUri = navigationUri;
                //     if (Convert.ToBoolean(ScheduledActionService.Find(name)))
                //     {
                //         ScheduledActionService.Remove(name);
                //         ScheduledActionService.Add(reminder);
                //     }
                //     else
                //     {
                //         ScheduledActionService.Add(reminder);
                //     }
                // }
                ToDoListData objToDoListData = new ToDoListData();
                objToDoListData.saveToDoList(Title, Description, cat, Date, Time, listid);
                NavigationService.RemoveBackEntry();
                NavigationService.GoBack();

            }
            catch (Exception ex)
            {
                QuickTaskDataContext context = new QuickTaskDataContext(App.ConnectionString);
                IQueryable<Reminders> reminder = from i in context.reminderalr where i.id.ToString() == remid select i;
                if (reminder.Count() > 0)
                {
                    foreach (var r in reminder)
                    {
                        reminderid = r.Rguid;
                        break;
                    }

                    if (ScheduledActionService.Find(reminderid) != null)
                    {
                        ScheduledActionService.Remove(reminderid);
                    }
                    Reminders rem = reminder.FirstOrDefault();
                    context.reminderalr.DeleteOnSubmit(rem);
                    context.SubmitChanges();
                }

                if (beginTime < DateTime.Now)
                {
                    MessageBoxResult result = MessageBox.Show("invalid date time");
                    if (result == MessageBoxResult.OK)
                    {
                        //NavigationService.RemoveBackEntry();
                        if(NavigationService.CanGoBack)
                        NavigationService.GoBack();
                    }
                }

                Exceptions.SaveOrSendExceptions("Exception in  ApplicationBarIconButton_Click event In RemindersAlarms.xaml page", ex);
            
            }

        }

       
    }
}